import { uiLogin } from '@/api/authorizationManagement'
import { getToken, setToken, removeToken } from '@/utils/auth'

const user = {
  state: {
    token: getToken(),
    userInfo: {},
    roles: (localStorage.getItem("ydRobotPermissions") ? JSON.parse(localStorage.getItem("ydRobotPermissions")) : []),
  },

  mutations: {
    SET_TOKEN: (state, token) => {
      state.token = token
    },
    SET_ROLES: (state, roles) => {
      state.roles = roles
    },
    SET_USER_INFO: (state, userIfno) => {
      state.userInfo = userIfno
    }
  },

  actions: {
    // 登录
    uiLogin({ commit }, userInfo) {
      userInfo.userId = userInfo.userId.trim()
      return new Promise((resolve, reject) => {
        uiLogin(userInfo).then(response => {
          setToken(response.token);
          commit('SET_TOKEN', response.token)
          if (!response.permissions || response.permissions.length === 0) {
            var data = JSON.stringify(["home"]);
            localStorage.setItem("ydRobotPermissions", data);
            commit('SET_ROLES', ["home"])
          } else {
            var data = JSON.stringify(
              response.permissions.map(item => item.sign)
            );
            localStorage.setItem("ydRobotPermissions", data);
            commit('SET_ROLES', response.permissions.map(item => item.sign))
          }
          this.$router.push({ path: "/" });
          resolve()
        }).catch(error => {
          reject(error)
        })
      })
    },
    // 登出
    uiLogout({ commit }) {
      return new Promise((resolve, reject) => {
        commit('SET_TOKEN', '')
        commit('SET_ROLES', [])
        removeToken()
        localStorage.clear();
        resolve()
        // uiLogout().then(response => {
        //   resolve()
        // }).catch(error => {
        //   reject(error)
        // })
      })
    },
    // 用户信息
    userInfo({ commit }, userInfo) {
      commit('SET_USER_INFO', userInfo)
    },
    // 用户权限
    LoginUserPermissions({ commit }, userPermissions) {
      commit('SET_ROLES', userPermissions)
    },
  }
}

export default user
